package com.stars.easyms.base.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.NonNull;

import java.util.Arrays;

/**
 * <p>className: PatternUtil</p>
 * <p>description: 正则表达式工具类</p>
 *
 * @author guoguifang
 * @version 1.7.2
 * @date 2021/1/27 10:34 下午
 */
public final class PatternUtil {

    private static final String[] EMPTY_STRING_ARRAY = {};

    public static final String WHITESPACE = "\\s*";

    public static final String WHITESPACE_SEPARATOR = "\\s+";

    public static final String COMMA_SEPARATOR = toWhitespaceSeparator(",");

    public static final String COMMA_OR_WHITESPACE_SEPARATOR = toWhitespaceSeparator(",") + "|" + WHITESPACE_SEPARATOR;

    public static String toWhitespaceSeparator(final String separator) {
        return WHITESPACE + separator + WHITESPACE;
    }

    /**
     * 根据逗号分割字符串：返回的String数组里每个字符串都不包含空字符串
     */
    @NonNull
    public static String[] splitWithComma(String str) {
        if (str == null) {
            return EMPTY_STRING_ARRAY;
        }
        return ignoreEmptyTokens(str.trim().split(COMMA_SEPARATOR));
    }

    /**
     * 根据空白字符分割字符串：返回的String数组里每个字符串都不包含空字符串
     */
    @NonNull
    public static String[] splitWithWhitespace(String str) {
        if (str == null) {
            return EMPTY_STRING_ARRAY;
        }
        return ignoreEmptyTokens(str.trim().split(WHITESPACE_SEPARATOR));
    }

    /**
     * 根据逗号或空白字符分割字符串：返回的String数组里每个字符串都不包含空字符串
     */
    @NonNull
    public static String[] splitWithCommaOrWhitespace(String str) {
        if (str == null) {
            return EMPTY_STRING_ARRAY;
        }
        return ignoreEmptyTokens(str.trim().split(COMMA_OR_WHITESPACE_SEPARATOR));
    }

    private static String[] ignoreEmptyTokens(String[] tokens) {
        return Arrays.stream(tokens).filter(StringUtils::isNotBlank).toArray(String[]::new);
    }

    private PatternUtil() {
    }
}
